package com.ruoyi.labdata.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.labdata.domain.LabFlowTask;
import com.ruoyi.labdata.domain.LabFlowTaskLog;
import com.ruoyi.labdata.service.ILabFlowTaskLogService;
import com.ruoyi.labdata.service.ILabFlowTaskService;

/**
 * 流程任务Controller
 * 
 * @author winner pan
 * @date 2022-03-10
 */
@RestController
@RequestMapping("/labdata/task")
public class LabFlowTaskController extends BaseController {
	@Autowired
	private ILabFlowTaskService labFlowTaskService;
	@Autowired
    private ILabFlowTaskLogService labFlowTaskLogService;
	//@Autowired
	//private ISysRoleService sysRoleService;
	

	/**
	 * 查询流程任务列表
	 */
	//@PreAuthorize("@ss.hasPermi('labdata:task:list')")
	@GetMapping("/todoList")
	public TableDataInfo todoList(LabFlowTask labFlowTask) {
		startPage();
		SysUser loginUser = SecurityUtils.getLoginUser().getUser();
		labFlowTask.setCreateBy(loginUser.getUserName());
		labFlowTask.setCreateById(loginUser.getUserId());
		List<LabFlowTask> list = labFlowTaskService.selectTodoTaskList(labFlowTask);
		return getDataTable(list);
	}

	/**
	 * 微信小程序流程任务列表
	 */
	//@PreAuthorize("@ss.hasPermi('labdata:task:list')")
	@GetMapping("/weChatTodoList")
	public TableDataInfo weChatTodoList(LabFlowTask labFlowTask) {
		startPage();
		SysUser loginUser = SecurityUtils.getLoginUser().getUser();
		labFlowTask.setCreateBy(loginUser.getUserName());
		labFlowTask.setCreateById(loginUser.getUserId());
		List<LabFlowTask> list = labFlowTaskService.selectTodoTaskList(labFlowTask);
		List<LabFlowTask> list1= list.stream().filter(labTask -> !labTask.getBusinessTypeOpt().equals("projectCreationApplication")).collect(Collectors.toList());
		return getDataTable(list1);
	}
	@GetMapping("/doneList")
	public TableDataInfo doneList(LabFlowTask labFlowTask) {
		startPage();
		SysUser loginUser = SecurityUtils.getLoginUser().getUser();
		labFlowTask.setCreateBy(loginUser.getUserName());
		labFlowTask.setCreateById(loginUser.getUserId());
		List<LabFlowTask> list = labFlowTaskService.selectDoneTaskList(labFlowTask);
		return getDataTable(list);
	}
	// @PreAuthorize("@ss.hasPermi('labdata:task:list')")
	@GetMapping("/list/{instanceId}")
	public AjaxResult listInstanceTask(@PathVariable Long instanceId) {
		List<LabFlowTask> list = labFlowTaskService.selectLabFlowTaskByInstanceId(instanceId);
		LabFlowTaskLog labFlowTaskLog = new LabFlowTaskLog();
		labFlowTaskLog.setInstanceId(instanceId);
		List<LabFlowTaskLog> logList = labFlowTaskLogService.selectLabFlowTaskLogList(labFlowTaskLog);
		SysUser loginUser = SecurityUtils.getLoginUser().getUser();
		//List<Integer> roleIds = sysRoleService.selectRoleListByUserId(loginUser.getUserId());
		for(int i=0;i<list.size();i++){
			LabFlowTask task = list.get(i);
			for(LabFlowTaskLog tasklog : logList){
				if(tasklog.getTaskId().longValue()==task.getTaskId().longValue()){
					if(task.getTaskLogList()==null){
						task.setTaskLogList(new ArrayList<LabFlowTaskLog>());
					}
					task.getTaskLogList().add(tasklog);
				}
			}
			if(task.getIsCurrentOpt()==1 && task.getNodeNo()<list.size()){//结束节点不会作为当前节点
				if(task.getSignUser()!=null){
					if(task.getSignUser().equals(loginUser.getUserName())){
						task.setCanReset(true);
					}
				}else{
					LabFlowTask lastTask = list.get(i-1);
					if(lastTask.getSignUser()!=null && lastTask.getSignUser().equals(loginUser.getUserName())){
						lastTask.setCanWithDraw(true);
					}
					if(isHasPermit(task.getNodeUsers(),loginUser.getUserId())){
						task.setCanSign(true);
					}
				}
				break;
			}
			if(task.getNodeNo()==list.size()){
				task.setEndNode(true);
			}
		}
		/*Object[] tasks = list.toArray();
		CollectionUtils.reverseArray(tasks);*/
		return AjaxResult.success(list);
	}
	
	private boolean isHasPermit(String taskUserIds, Long userId){
		if(taskUserIds==null){
			return false;
		}
		String[] taskUserIdArr = taskUserIds.split(",");
		for(String item : taskUserIdArr){
			if(Long.valueOf(item)==userId.longValue()){
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 检查用户操作权限.
	 */
	//@PreAuthorize("@ss.hasPermi('labdata:task:query')")
	@GetMapping(value = "/permit/{instanceId}")
	public AjaxResult permit(@PathVariable("instanceId") Long instanceId) {
		SysUser loginUser = SecurityUtils.getLoginUser().getUser();
		LabFlowTask queryTask = new LabFlowTask();
		queryTask.setInstanceId(instanceId);
		queryTask.setCreateBy(loginUser.getUserName());
		return AjaxResult.success(labFlowTaskService.checkUserTaskPermit(queryTask));
	}
	
	/**
	 * 签收任务.
	 */
	//@PreAuthorize("@ss.hasPermi('labdata:task:query')")
	@GetMapping(value = "/sign/{taskId}")
	public AjaxResult signTask(@PathVariable("taskId") Long taskId) {
		return AjaxResult.success(labFlowTaskService.signedTask(taskId));
	}
	
	/**
	 * 签收任务.
	 */
	//@PreAuthorize("@ss.hasPermi('labdata:task:query')")
	@GetMapping(value = "/withdraw/{taskId}")
	public AjaxResult withdrawTask(@PathVariable("taskId") Long taskId) {
		return AjaxResult.success(labFlowTaskService.withDraw(taskId));
	}
	
	@PostMapping(value = "/compeleted")
	public AjaxResult compeletedTask(@RequestBody LabFlowTask labFlowTask) {
		return AjaxResult.success(labFlowTaskService.completedTask(labFlowTask));
	}
	@GetMapping(value = "/reset/{taskId}")
	public AjaxResult compeletedTask(@PathVariable("taskId") Long taskId) {
		return AjaxResult.success(labFlowTaskService.resetTask(taskId));
	}

	/**
	 * 导出流程任务列表
	 */
	@PreAuthorize("@ss.hasPermi('labdata:task:export')")
	@Log(title = "流程任务", businessType = BusinessType.EXPORT)
	@GetMapping("/export")
	public AjaxResult export(LabFlowTask labFlowTask) {
		List<LabFlowTask> list = labFlowTaskService.selectLabFlowTaskList(labFlowTask);
		ExcelUtil<LabFlowTask> util = new ExcelUtil<LabFlowTask>(LabFlowTask.class);
		return util.exportExcel(list, "task");
	}

	/**
	 * 获取流程任务详细信息
	 */
	@PreAuthorize("@ss.hasPermi('labdata:task:query')")
	@GetMapping(value = "/{taskId}")
	public AjaxResult getInfo(@PathVariable("taskId") Long taskId) {
		return AjaxResult.success(labFlowTaskService.selectLabFlowTaskById(taskId));
	}

	/**
	 * 新增流程任务
	 */
	@PreAuthorize("@ss.hasPermi('labdata:task:add')")
	@Log(title = "流程任务", businessType = BusinessType.INSERT)
	@PostMapping
	public AjaxResult add(@RequestBody LabFlowTask labFlowTask) {
		return toAjax(labFlowTaskService.insertLabFlowTask(labFlowTask));
	}

	/**
	 * 修改流程任务
	 */
	@PreAuthorize("@ss.hasPermi('labdata:task:edit')")
	@Log(title = "流程任务", businessType = BusinessType.UPDATE)
	@PutMapping
	public AjaxResult edit(@RequestBody LabFlowTask labFlowTask) {
		return toAjax(labFlowTaskService.updateLabFlowTask(labFlowTask));
	}

	/**
	 * 删除流程任务
	 */
	@PreAuthorize("@ss.hasPermi('labdata:task:remove')")
	@Log(title = "流程任务", businessType = BusinessType.DELETE)
	@DeleteMapping("/{taskIds}")
	public AjaxResult remove(@PathVariable Long[] taskIds) {
		return toAjax(labFlowTaskService.deleteLabFlowTaskByIds(taskIds));
	}
}
